import {
  Form,
  Button,
  Card,
  Breadcrumb,
  Radio,
  Select,
  DatePicker,
  Table,
  Space,
  Tag,
  Image,
  Modal,
} from "antd"
import { EditOutlined, DeleteOutlined } from "@ant-design/icons"
import { Link } from "react-router-dom"
import styles from "./index.module.scss"
import { useChannels } from "@/utils/g_hooks"
import { useState, useEffect, useRef } from "react"
import { useHistory } from "react-router-dom"
import http from "@/utils/http"
import defaultImg from "@/assets/error.png"

const statusLabel = [
  { text: "草稿", color: "default" },
  { text: "待审核", color: "blue" },
  { text: "审核通过", color: "green" },
  { text: "审核拒绝", color: "red" },
]

const Article = () => {
  const channels = useChannels() // 得到一个状态
  const history = useHistory()
  // 管理列表状态
  const [article, setArticle] = useState({
    page: 1, // 第几页
    per_page: 10, // 每页多少条
    results: [], // 列表数据
    total_count: 0, // 总数
  })
  const { results, total_count, page, per_page } = article // 解构取出总数和列表数据
  // useRef是一个可以存储数据的对象- 并不会造成页面的刷新
  const paramsRef = useRef({
    page: 1,
    per_page: 10,
    status: undefined,
    channel_id: null,
    begin_pubdate: undefined,
    end_pubdate: undefined,
  })

  const getArticleList = async (params) => {
    const data = await http.get("/mp/articles", { params })
    setArticle(data) // 将数据设置给状态
  }
  // 删除方法
  const delArticle = (id) => {
    // 1.提示是否删除
    Modal.confirm({
      title: "提示",
      content: "确认要删除该文章吗",
      async onOk() {
        // 点击了确定
        // 调用删除接口
        await http.delete("/mp/articles/" + id) // 删除文章
        getArticleList(paramsRef.current) //带上原来的参数 进行再次查询
      },
    })
  }
  // 去编辑
  const toEdit = (id) => {
    history.push("/home/publish/" + id) //跳转到发布页面
  }
  // 获取列表数据
  useEffect(() => {
    getArticleList()
  }, [])
  const columns = [
    {
      title: "封面",
      dataIndex: "cover",
      key: "cover",
      render: (cover) => (
        <Image
          src={cover?.images?.[0] || defaultImg}
          width={200}
          height={120}
        ></Image>
      ),
    },
    {
      title: "标题",
      dataIndex: "title",
      key: "title",
    },
    {
      title: "状态",
      dataIndex: "status",
      key: "status",
      render: (value) => (
        <Tag color={statusLabel[value].color}>{statusLabel[value].text}</Tag>
      ),
    },
    {
      title: "发布时间",
      dataIndex: "pubdate",
      key: "pubdate",
    },
    {
      title: "阅读数",
      dataIndex: "read_count",
      key: "read_count",
    },
    {
      title: "评论数",
      dataIndex: "comment_count",
      key: "comment_count",
    },
    {
      title: "点赞数",
      dataIndex: "like_count",
      key: "like_count",
    },
    {
      title: "操作",
      key: "action",
      render: (_, row) => (
        <Space size="middle">
          <Button
            onClick={() => toEdit(row.id)}
            type="link"
            icon={<EditOutlined />}
          />
          <Button
            type="link"
            onClick={() => delArticle(row.id)}
            icon={<DeleteOutlined />}
          />
        </Space>
      ),
    },
  ]
  const onFinish = (values) => {
    // 进行一些处理

    paramsRef.current.status = values.status
    paramsRef.current.channel_id = values.channel_id
    if (values.dateArr?.length) {
      // 有开始时间和结束时间
      paramsRef.current.begin_pubdate = values.dateArr[0].format(
        "YYYY-MM-DD HH:mm:ss"
      )
      paramsRef.current.end_pubdate = values.dateArr[1].format(
        "YYYY-MM-DD HH:mm:ss"
      )
    } else {
      paramsRef.current.begin_pubdate = undefined
      paramsRef.current.end_pubdate = undefined
    }
    paramsRef.current.page = 1 // 条件的变化 重新查第一页
    // 发起请求- 携带参数
    getArticleList(paramsRef.current)
  }
  const onPageChange = (currentPage) => {
    // 可以拿到最新的页码
    // const params = {
    //   page: currentPage,
    //   per_page,
    // }
    paramsRef.current.page = currentPage // 只改变了 页码

    // 还存留着之前的筛选条件的数据
    getArticleList(paramsRef.current) // 发起请求，做分页
  }
  return (
    <div className={styles.root}>
      <Card
        title={
          // 面包屑
          <Breadcrumb>
            <Breadcrumb.Item>
              <Link to="/">首页</Link>
            </Breadcrumb.Item>
            <Breadcrumb.Item>内容管理</Breadcrumb.Item>
          </Breadcrumb>
        }
      >
        {/* 表单 */}
        <Form onFinish={onFinish}>
          <Form.Item name="status" label="状态：">
            <Radio.Group>
              <Radio value={undefined}>全部</Radio>
              <Radio value={0}>草稿</Radio>
              <Radio value={1}>待审核</Radio>
              <Radio value={2}>已通过</Radio>
              <Radio value={3}>已拒绝</Radio>
            </Radio.Group>
          </Form.Item>
          <Form.Item name="channel_id" label="频道：">
            <Select style={{ width: 300 }}>
              {channels.map((item) => (
                <Select.Option key={item.id} value={item.id}>
                  {item.name}
                </Select.Option>
              ))}
            </Select>
          </Form.Item>
          <Form.Item name="dateArr" label="日期：">
            {/* 日期范围 */}
            <DatePicker.RangePicker></DatePicker.RangePicker>
          </Form.Item>
          <Form.Item>
            <Button type="primary" htmlType="submit">
              筛选
            </Button>
          </Form.Item>
        </Form>
      </Card>
      {/* 列表的卡片 */}
      <Card
        title={`根据筛选条件共查询到 ${total_count} 条结果：`}
        style={{ marginTop: 24 }}
      >
        <Table
          rowKey="id"
          columns={columns}
          dataSource={results}
          pagination={{
            // 配置项
            current: page, // 当前页码
            pageSize: per_page, // 每页多少条
            total: total_count, // 总数
            onChange: onPageChange,
          }}
        ></Table>
      </Card>
    </div>
  )
}

export default Article
